package com.kerrykidz.filemanagement.service.impl;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kerrykidz.common.Constants;
import com.kerrykidz.common.PrimaryKeyGenerator;
import com.kerrykidz.common.PrimaryKeyGenerator.BusinessType;
import com.kerrykidz.dao.model.LocPerInoutEntity;
import com.kerrykidz.filemanagement.dao.mapper.LocPerInoutEntityMapper;
import com.kerrykidz.filemanagement.service.ISiteService;
import com.kerrykidz.membership.dao.mapper.CusCouponEntityMapper;
import com.kerrykidz.membership.dao.mapper.CusMemEntityMapper;
import com.kerrykidz.membership.dao.mapper.CusMemHisEntityMapper;
import com.kerrykidz.membership.dao.model.CusGuaEntity;
import com.kerrykidz.membership.dao.model.CusMemEntity;
import com.kerrykidz.membership.dao.model.CusMemHisEntity;
import com.kerrykidz.scminvoicing.dao.mapper.GblScmPrdMemEntityMapper;
import com.kerrykidz.scminvoicing.dao.model.GblScmPrdMemEntity;
import com.kerrykidz.system.util.DateUtil;
import com.rdp.framework.core.model.MyBatisSuperModel;
import com.rdp.framework.exception.RDPException;
import com.rdp.util.config.PropertiesUtil;

/**
 * 访客管理服务实现类
 * @author YJJ
 *
 */
@Service
public class SiteServiceImpl implements ISiteService {

	private Logger loger = LoggerFactory.getLogger(SiteServiceImpl.class);
	@Autowired
	private LocPerInoutEntityMapper locPerInoutEntityMapper;
	@Autowired
	private CusMemEntityMapper memMapper;
	@Autowired
	private GblScmPrdMemEntityMapper gblScmPrdMemEntityMapper;
	@Autowired
	private CusMemHisEntityMapper cusMemHisEntityMapper;
	@Autowired
	private CusCouponEntityMapper couponEntityMapper;
	
	public List<LocPerInoutEntity> getAllPerInOut(MyBatisSuperModel model) {
		model.setIspaging(true);
		return locPerInoutEntityMapper.getAllPerInOut(model);
	}
	
	/**
	 * 保存实体(进场)
	 * @return
	 * @throws Exception 
	 */
	public String insertLocPerInOut(HttpServletRequest request, String inMemberIds, String inGuaIds, String receivePwds, String type, String saleId, String userId, String branId, String abbrCode, String familyId) throws Exception{
		// 修改进场会员的进场时间(由于单人没预约，需要新增一条)
		if(null!=inMemberIds && !"".equals(inMemberIds)){
			String[] inMemberIdArray = inMemberIds.split(",");
			if (null != inMemberIdArray && inMemberIdArray.length > 0) {
				for (int i = 0; i < inMemberIdArray.length; i++) {
					String memberId=inMemberIdArray[i];
					LocPerInoutEntity locPerInout = new LocPerInoutEntity();
					String pkPerIoId = PrimaryKeyGenerator.getPrimaryKey(BusinessType.PE, abbrCode);
					locPerInout.setPkPerIoId(pkPerIoId);
					locPerInout.setFkBranId(branId);
					if (null != type && "3".equals(type)) {
						type = "5";// 访客
					}
					locPerInout.setType(type);
					locPerInout.setFamBatch(familyId);
					locPerInout.setFkMemId(memberId);
					if (null != type && "5".equals(type)) {// 访客才有
						locPerInout.setFkUsrId(saleId);
					}
					locPerInout.setOperateBy(userId);
					locPerInoutEntityMapper.saveEntity(locPerInout);
					
					//激活会员，并算出会员有效期
					if (null != type && "1".equals(type)) {
						CusMemEntity member = null;
						try {
							member = memMapper.findEntityById(memberId);//修改会员表
						} catch (Exception e) {
							e.printStackTrace();
						}
						if(null!=member){
							String memType=member.getMemType();
							String status=member.getStatus();
							
							String hisType=null;
							if(null!=memType && "1".equals(member.getMemType())){
								if(null!=status && "4".equals(status)){
									hisType=Constants.MEM_HIS_TYPE_TICKET;
								}else{
									hisType=Constants.MEM_HIS_TYPE_MEMBER;
								}
							}else{
								hisType=Constants.MEM_HIS_TYPE_TICKET;
							}
							List<CusMemHisEntity> cusMemHiss = cusMemHisEntityMapper.findEntityByMembIds(memberId, hisType);//修改历史表
							
							//未激活状态时，过期状态时算有效期等等(会员)
							if(status.equals("1")){
								member.setStatus(Constants.MEMBER_STATUS_VALID);//状态切换
								member.setModiBy(userId);
								
								//购买会籍，非续会
								GblScmPrdMemEntity gblScmPrdMem = gblScmPrdMemEntityMapper.getPrdMembyMebId(memberId);
								if(null!=gblScmPrdMem){
									Date memStartDate=member.getStartDate();
									Date memEndDate=member.getEndDate();
									Date memModiTime=member.getModiTime();
									int month=gblScmPrdMem.getMonth();
									Date startDate=new Date();
									Date endDate = null;
									
									if (null!=memStartDate && !memStartDate.equals("")){
										//第二次开始进来时
										int startPlusDays=DateUtil.getDiffDays(memStartDate, memModiTime);
										int endPlusDays=DateUtil.getDiffDays(memModiTime, memEndDate);//失效日期-续会日期
										if((null!=memStartDate && !"".equals(memStartDate)) && (null!=memEndDate && !"".equals(memEndDate)) && (null!=memModiTime && !"".equals(memModiTime)) && (startPlusDays>=0) && (endPlusDays>=0)){
											//会员期内续会时
											endDate=DateUtil.addMonth2Date(month, startDate);
											endDate=DateUtil.addDay2Date(endPlusDays+1, endDate);//失效日期加上差数再加1
										}else{
											endDate=DateUtil.addMonth2Date(month, startDate);
										}
									}else{
										//第一次进来时（为nul时）
										endDate=DateUtil.addMonth2Date(month, startDate);
									}
									
									//格式化日期为年-月-日
									if(null!=startDate){
										startDate=DateUtil.getDate(DateUtil.formatDate("yyyy-MM-dd", startDate));
									}
									if(null!=endDate){
										endDate=DateUtil.getDate(DateUtil.formatDate("yyyy-MM-dd", endDate));
									}
											
									member.setStartDate(startDate);
									member.setEndDate(endDate);
									
									//设置会员历史数据
									if(null!=cusMemHiss){
										for (int j = 0; j < cusMemHiss.size(); j++) {
											CusMemHisEntity cusMemHis=cusMemHiss.get(i);
											cusMemHis.setStartDate(startDate);
											cusMemHis.setEndDate(endDate);
										}
									}
									
									//修改玩伴券有效期
									couponEntityMapper.updateCouponBymemId(memberId, startDate, endDate);
								}else{
									throw new Exception("设定会有有效期失败!");
								}
								
							}else{// if(status.equals("2"))  还包含停卡购买单次票进场的
								//(非会员)
								//只有单次票才改历史使用状态
								if (null != memType && !"3".equals(memType)) {
									if(null!=cusMemHiss){
										for (int j = 0; j < cusMemHiss.size(); j++) {
											CusMemHisEntity cusMemHis=cusMemHiss.get(i);
											cusMemHis.setUserStatus("0");//已使用
										}
									}
								}
							}
							
							//修改会员历史
							if(null!=cusMemHiss){
								for (int j = 0; j < cusMemHiss.size(); j++) {
									CusMemHisEntity cusMemHis=cusMemHiss.get(i);
									cusMemHis.setFkOrderId(null);
									cusMemHis.setFkPrdId(null);
									cusMemHisEntityMapper.updateEntityByMembId(cusMemHis);
								}
							}
							
							//当receivePwds不为空时给全部会员设置统一接领密码
							if(null!=receivePwds && !"".equals(receivePwds)){
								member.setReceivePwd(receivePwds);
							}
							memMapper.updateEntity(member);
						}
					}
				}
			}
		}

		// 修改进场监护人的进场时间(由于单人没预约，需要新增一条)
		if(null!=inGuaIds && !"".equals(inGuaIds)){
			String[] inGuaIdArray = inGuaIds.split(",");
			if (null != inGuaIdArray && inGuaIdArray.length > 0) {
				for (int i = 0; i < inGuaIdArray.length; i++) {
					LocPerInoutEntity locPerInout = new LocPerInoutEntity();
					String pkPerIoId = PrimaryKeyGenerator.getPrimaryKey(
							BusinessType.PE, abbrCode);
					locPerInout.setPkPerIoId(pkPerIoId);
					locPerInout.setFkBranId(branId);
					if (null != type && "3".equals(type)) {
						type = "5";// 访客
					}
					locPerInout.setType(type);
					locPerInout.setFamBatch(familyId);
					locPerInout.setFkGuaId(inGuaIdArray[i]);
					locPerInout.setOperateBy(userId);
					locPerInoutEntityMapper.saveEntity(locPerInout);
				}
			}
		}
		
		//调用门禁开门(改为客户端调用)
		//String batPath = request.getServletContext().getRealPath("/")+"WEB-INF\\classes\\properties\\opendoor.bat";
		PropertiesUtil prop = new PropertiesUtil();
		String batPath = prop.readSingleProps("DOOR_CONTROL_PATH", "/properties/kerrykidz.properties");
		/*Process process=Runtime.getRuntime().exec("cmd /c "+batPath);
		process.waitFor();
		process.destroy();*/
		
		return batPath;
	}

	/**
	 * 更新实体(出场)
	 * @return
	 * @throws IOException 
	 * @throws InterruptedException 
	 */
	public String updateLocPerInOut(HttpServletRequest request, String inMemberIds, String inGuaIds)throws RDPException, IOException, InterruptedException{
		// 修改出场会员的进场时间(由于单人没预约，需要新增一条)
		if (null != inMemberIds && !"".equals(inMemberIds)) {
			String[] inMemberIdArray = inMemberIds.split(",");
			if (null != inMemberIdArray && inMemberIdArray.length > 0) {
				for (int i = 0; i < inMemberIdArray.length; i++) {
					//此处续会后多条记录，需要加上已使用的条件判断(存在有效期的)
					CusMemEntity member = memMapper.findMemberById(inMemberIdArray[i]);//修改会员状态
					if(null!=member){
						if(Constants.MEM_TYPE_NOTMEMBER.equals(member.getMemType())){
							//如果是非会员，则改为失效
							member.setStatus(Constants.MEMBER_STATUS_OVERDUE);
							//如果还有会员卡呢，有需要改为未激活
							memMapper.updateEntity(member);
						}/*else if(Constants.MEM_TYPE_MEMBER.equals(member.getMemType())){
							//如果是会员，如果今天是到期时间则改为过期，否则不改
							member.setStatus(Constants.MEMBER_STATUS_OVERDUE);
							memMapper.updateEntity(member);
						}*/
					}
					
					locPerInoutEntityMapper.updateEntityById(inMemberIdArray[i], null);//修改出场时间
				}
			}
		}

		// 修改出场监护人的进场时间(由于单人没预约，需要新增一条)
		if (null != inGuaIds && !"".equals(inGuaIds)) {
			String[] inGuaIdArray = inGuaIds.split(",");
			if (null != inGuaIdArray && inGuaIdArray.length > 0) {
				for (int i = 0; i < inGuaIdArray.length; i++) {
					locPerInoutEntityMapper.updateEntityById(null, inGuaIdArray[i]);
				}
			}
		}
		
		// 调用门禁出场(改为客户端调用)
		//String batPath = request.getServletContext().getRealPath("/")+"WEB-INF\\classes\\properties\\opendoor.bat";
		PropertiesUtil prop = new PropertiesUtil();
		String batPath = prop.readSingleProps("DOOR_CONTROL_PATH", "/properties/kerrykidz.properties");
		/*Process process = Runtime.getRuntime().exec("cmd /c " + batPath);
		process.waitFor();
		process.destroy();*/
		
		return batPath;
	}

	public List<CusGuaEntity> getCusGuaList(String familyId) throws RDPException {
		return locPerInoutEntityMapper.getCusGuaList(familyId);
	}

	public List<LocPerInoutEntity> getLocPerInOutByMemId(String memberId)
			throws RDPException {
		return locPerInoutEntityMapper.getLocPerInOutByMemId(memberId);
	}

	public void updateCouponBymemId(String fkMemId, Date validFrom, Date validTo) throws RDPException {
		couponEntityMapper.updateCouponBymemId(fkMemId, validFrom, validTo);
	}
}
